package com.gxnu.edu.cn.client.ui;

import com.gxnu.edu.cn.client.controller.*;
import com.gxnu.edu.cn.ttxxt.entity.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;

import java.util.*;
import java.util.Map;
import java.util.Timer;
import java.util.concurrent.CompletableFuture;

@Component
public class MainFrame extends JFrame {
    private String username;
    private String serverIp;
    private Long userId;
    private JTextArea messageArea;
    private JTextField messageInput;
    private JButton sendButton;
    private JList<String> friendList;
    private JList<String> groupList;
    private JList<String> favoriteList;
    private DefaultListModel<String> groupListModel;
    private DefaultListModel<String> friendListModel;
    private DefaultListModel<String> favoriteListModel;
    private Long currentChatId;
    private Boolean isGroupChat = false;
    private Font currentFont = new Font("SimHei", Font.PLAIN, 14); // 当前字体设置

    // 新增：通知未读计数
    private JLabel notificationBadge;

    @Autowired
    private UserClient userClient;
    @Autowired
    private GroupClient groupClient;
    @Autowired
    private FriendClient friendClient;
    @Autowired
    private MessageClient messageClient;
    @Autowired
    private NotificationClient notificationClient;
    @Autowired
    private FavoriteClient favoriteClient;
    @Autowired
    private FileClient fileClient;
    @Autowired
    private FontSettingClient fontSettingClient;

    // 新增成员变量声明
    private JTextField searchField;
    private JButton searchButton;
    private JComboBox<String> searchTypeCombo;
    private String signature;
    private String phone;
    private String email;
    private String avatarUrl;

    public MainFrame() {
        setTitle("即时通讯软件");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        initComponents();
        System.out.println("MainFrame初始化完成");
    }

    public void init(String username, String serverIp) {
        this.username = username;
        this.serverIp = serverIp; // 保存服务器 IP 地址
        setTitle("即时通讯软件 - " + username);
        setTitle("即时通讯软件 - " + username);

        // 获取用户信息并设置userId
        userClient.getUserByUsername(username).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    this.userId = Long.valueOf(data.get("userId").toString());
                    System.out.println("获取用户 ID 成功: " + userId);
                    initData();

                    // 加载用户字体设置
                    loadFontSettings();
                }
            } else {
                System.err.println("获取用户信息失败，用户名为: " + username);
                JOptionPane.showMessageDialog(this, "获取用户信息失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        }).exceptionally(ex -> {
            System.err.println("获取用户信息异常: " + ex.getMessage());
            JOptionPane.showMessageDialog(this, "获取用户信息异常: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return null;
        });

    }

    private void initComponents() {
        // 创建主分割面板
        JSplitPane mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);

        // 创建左侧面板（包含选项卡）
        JTabbedPane leftTabbedPane = new JTabbedPane();
        leftTabbedPane.setPreferredSize(new Dimension(800, 600));
        // 好友列表
        friendListModel = new DefaultListModel<>();
        friendList = new JList<>(friendListModel);
        friendList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = friendList.locationToIndex(e.getPoint());
                    if (index >= 0) {
                        String friendName = friendListModel.getElementAt(index);
                        onFriendSelected(friendName);
                    }
                } else if (e.getButton() == MouseEvent.BUTTON3) {
                    // 右键菜单
                    showFriendContextMenu(e, friendListModel.getElementAt(friendList.locationToIndex(e.getPoint())));
                }
            }
        });
        JScrollPane friendScrollPane = new JScrollPane(friendList);
        friendScrollPane.setBorder(BorderFactory.createTitledBorder("好友列表"));
        leftTabbedPane.addTab("好友列表", friendScrollPane);

        // 群组列表
        groupListModel = new DefaultListModel<>();
        groupList = new JList<>(groupListModel);
        groupList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = groupList.locationToIndex(e.getPoint());
                    if (index >= 0) {
                        String groupName = groupListModel.getElementAt(index);
                        onGroupSelected(groupName);
                    }
                } else if (e.getButton() == MouseEvent.BUTTON3) {
                    // 右键菜单
                    showGroupContextMenu(e, groupListModel.getElementAt(groupList.locationToIndex(e.getPoint())));
                }
            }
        });
        JScrollPane groupScrollPane = new JScrollPane(groupList);
        groupScrollPane.setBorder(BorderFactory.createTitledBorder("群组列表"));
        leftTabbedPane.addTab("群组列表", groupScrollPane);

        // 常用联系人
        favoriteListModel = new DefaultListModel<>();
        favoriteList = new JList<>(favoriteListModel);
        favoriteList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 2) {
                    int index = favoriteList.locationToIndex(e.getPoint());
                    if (index >= 0) {
                        String favoriteName = favoriteListModel.getElementAt(index);
                        onFavoriteSelected(favoriteName);
                    }
                } else if (e.getButton() == MouseEvent.BUTTON3) {
                    // 右键菜单
                    showFavoriteContextMenu(e, favoriteListModel.getElementAt(favoriteList.locationToIndex(e.getPoint())));
                }
            }
        });
        JScrollPane favoriteScrollPane = new JScrollPane(favoriteList);
        favoriteScrollPane.setBorder(BorderFactory.createTitledBorder("常用联系人"));
        leftTabbedPane.addTab("常用联系人", favoriteScrollPane);

//        // 设置左侧面板大小
//        leftTabbedPane.setPreferredSize(new Dimension(200, 600));
        mainSplitPane.setLeftComponent(leftTabbedPane);

        // 创建右侧面板（聊天界面）
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BorderLayout());

        // 聊天标题栏
        JPanel titlePanel = new JPanel();
        titlePanel.setLayout(new BorderLayout());
        titlePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        JLabel chatTitle = new JLabel("选择联系人开始聊天");
        chatTitle.setFont(new Font("SimHei", Font.BOLD, 16));
        titlePanel.add(chatTitle, BorderLayout.CENTER);
        rightPanel.add(titlePanel, BorderLayout.NORTH);

        // 消息显示区域
        messageArea = new JTextArea();
        messageArea.setEditable(false);
        messageArea.setLineWrap(true);
        messageArea.setWrapStyleWord(true);
        messageArea.setFont(currentFont); // 使用当前字体
        JScrollPane messageScrollPane = new JScrollPane(messageArea);
        messageScrollPane.setBorder(BorderFactory.createTitledBorder("消息显示区域"));
        rightPanel.add(messageScrollPane, BorderLayout.CENTER);

        // 消息输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        messageInput = new JTextField();
        messageInput.setFont(currentFont); // 使用当前字体
        sendButton = new JButton("发送");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });
        messageInput.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        inputPanel.add(messageInput, BorderLayout.CENTER);
        inputPanel.add(sendButton, BorderLayout.EAST);
        inputPanel.setBorder(BorderFactory.createTitledBorder("消息输入区域"));
        rightPanel.add(inputPanel, BorderLayout.SOUTH);

        mainSplitPane.setRightComponent(rightPanel);

        // 设置分割面板的分割位置
        mainSplitPane.setDividerLocation(200);

        // 添加菜单栏
        JMenuBar menuBar = new JMenuBar();

        // 文件菜单
        JMenu fileMenu = new JMenu("退出");
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        fileMenu.add(exitItem);
        menuBar.add(fileMenu);

        // 联系人菜单
        JMenu contactMenu = new JMenu("联系人");
        JMenuItem addFriendItem = new JMenuItem("添加好友");
        addFriendItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String friendUsername = JOptionPane.showInputDialog(
                        MainFrame.this,
                        "请输入要添加的好友用户名:",
                        "添加好友",
                        JOptionPane.QUESTION_MESSAGE
                );

                if (friendUsername != null && !friendUsername.isEmpty()) {
                    System.out.println("开始处理添加好友请求，用户名为: " + friendUsername);
                    // 实现添加好友功能
                    userClient.getUserByUsername(friendUsername).thenAccept(friendInfo -> {
                        if (friendInfo != null && friendInfo.get("code") != null && friendInfo.get("code").equals(200)) {
                            Map<String, Object> data = (Map<String, Object>) friendInfo.get("data");
                            if (data != null) {
                                Long friendId = Long.valueOf(data.get("userId").toString());
                                System.out.println("找到用户，ID: " + friendId);
                                Map<String, Object> request = new HashMap<>();
                                request.put("senderId", userId);
                                request.put("receiverId", friendId);
                                request.put("message", "你好，我想添加你为好友"); // 添加默认消息
                                friendClient.sendFriendRequest(request).thenAccept(response -> {
                                    SwingUtilities.invokeLater(() -> {
                                        if (response.get("status").equals("success")) {
                                            JOptionPane.showMessageDialog(
                                                    MainFrame.this,
                                                    "好友请求已发送",
                                                    "提示",
                                                    JOptionPane.INFORMATION_MESSAGE
                                            );
                                            // 刷新好友列表
                                            refreshFriendList();
                                        } else {
                                            JOptionPane.showMessageDialog(
                                                    MainFrame.this,
                                                    "添加好友失败: " + response.get("message"),
                                                    "错误",
                                                    JOptionPane.ERROR_MESSAGE
                                            );
                                        }
                                    });
                                });
                            }
                        } else {
                            SwingUtilities.invokeLater(() -> {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "用户不存在",
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            });
                            System.err.println("用户不存在，用户名为: " + friendUsername);
                        }
                    });
                }
            }
        });

        // 新增：好友请求管理
        JMenuItem friendRequestsItem = new JMenuItem("好友请求");
        friendRequestsItem.addActionListener(e -> showFriendRequestsDialog());

        contactMenu.add(addFriendItem);
        contactMenu.add(friendRequestsItem);
        menuBar.add(contactMenu);

        // 群组菜单
        JMenu groupMenu = new JMenu("群组");
        JMenuItem createGroupItem = new JMenuItem("创建群组");
        createGroupItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String groupName = JOptionPane.showInputDialog(
                        MainFrame.this,
                        "请输入群组名称:",
                        "创建群组",
                        JOptionPane.QUESTION_MESSAGE
                );

                if (groupName != null && !groupName.isEmpty()) {
                    System.out.println("开始创建群组，群名为: " + groupName);
                    Map<String, String> request = Map.of("groupName", groupName, "creatorId", String.valueOf(userId));
                    groupClient.createGroup(request).thenAccept(group -> {
                        SwingUtilities.invokeLater(() -> {
                            if (group != null) {
                                groupListModel.addElement(group.getGroupName());
                                System.out.println("群组创建成功，ID: " + group.getGroupId());
                            } else {
                                System.err.println("群组创建失败");
                            }
                        });
                    });
                }
            }
        });

        // 新增：我的群组管理
        JMenuItem myGroupsItem = new JMenuItem("我的群组");
        myGroupsItem.addActionListener(e -> showMyGroupsDialog());

        groupMenu.add(createGroupItem);
        groupMenu.add(myGroupsItem);
        menuBar.add(groupMenu);


        // 添加搜索栏到左侧面板上方
        JPanel searchPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        searchPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

        searchField = new JTextField(15);
        searchButton = new JButton("搜索");
        searchTypeCombo = new JComboBox<>(new String[]{"好友", "群组"});

// 设置组件的首选大小，确保布局合理
        searchTypeCombo.setPreferredSize(new Dimension(70, 25));
        searchButton.setPreferredSize(new Dimension(70, 25));

        searchPanel.add(searchTypeCombo, BorderLayout.WEST);
        searchPanel.add(searchField, BorderLayout.CENTER);
        searchPanel.add(searchButton, BorderLayout.EAST);

        leftTabbedPane.add(searchPanel, "搜索"); // 添加到选项卡上方
        leftTabbedPane.setSelectedIndex(0); // 默认显示好友列表


        // 搜索按钮事件
        searchButton.addActionListener(e -> performSearch());
        searchField.addActionListener(e -> performSearch());

        // 个人中心菜单
        JMenu userMenu = new JMenu("个人中心");
        JMenuItem profileItem = new JMenuItem("个人资料");
        profileItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (username == null || username.isEmpty()) {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "未登录，无法查看个人资料",
                            "提示",
                            JOptionPane.WARNING_MESSAGE
                    );
                    System.out.println("未登录，无法查看个人资料");
                    return;
                }

                // 获取用户信息
                System.out.println("开始获取个人资料，用户名为: " + username);
                userClient.getUserByUsername(username).whenComplete((userInfo, ex) -> {
                    SwingUtilities.invokeLater(() -> {
                        if (ex != null) {
                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    "获取个人资料失败: " + ex.getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                            System.err.println("获取个人资料异常: " + ex.getMessage());
                            return;
                        }

                        if (userInfo == null || !userInfo.get("code").equals(200)) {
                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    "获取个人资料失败",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                            System.err.println("获取个人资料失败，用户不存在");
                            return;
                        }

                        Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                        userId = Long.valueOf(data.get("userId").toString());
                        // 显示个人资料
                        StringBuilder profileInfo = new StringBuilder();
                        profileInfo.append("用户名: ").append(data.get("username")).append("\n");
                        profileInfo.append("用户ID: ").append(data.get("userId"));
                        String phone = (String) data.get("phone");
                        profileInfo.append("联系电话: ").append(phone != null ? phone : "未绑定").append("\n");

                        String email = (String) data.get("email");
                        profileInfo.append("电子邮箱: ").append(email != null ? email : "未绑定").append("\n");

// 3. 个人资料（头像、签名）
//                        String avatarUrl = (String) data.get("avatarUrl");
//                        profileInfo.append("头像地址: ").append(avatarUrl != null ? avatarUrl : "default_avatar.png").append("\n");

                        String signature = (String) data.get("signature");
                        profileInfo.append("个人签名: ").append(signature != null ? signature : "这家伙很懒，什么都没留下").append("\n");

// 4. 账号状态
//                        Integer status = (Integer) data.get("status");
//                        profileInfo.append("账号状态: ").append(status != null ? (status == 1 ? "正常" : "禁用") : "未知").append("\n");
//
//// 5. 时间信息（创建时间、更新时间）
//                        Object createTimeObj = data.get("createTime");
//                        if (createTimeObj instanceof LocalDateTime) {
//                            LocalDateTime createTime = (LocalDateTime) createTimeObj;
//                            profileInfo.append("注册时间: ").append(createTime.format(
//                                    java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
//                        } else {
//                            profileInfo.append("注册时间: 未知").append("\n");
//                        }
//
//                        Object updateTimeObj = data.get("updateTime");
//                        if (updateTimeObj instanceof LocalDateTime) {
//                            LocalDateTime updateTime = (LocalDateTime) updateTimeObj;
//                            profileInfo.append("最后更新: ").append(updateTime.format(
//                                    java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))).append("\n");
//                        } else {
//                            profileInfo.append("最后更新: 未更新").append("\n");
//                        }

//                        profileInfo.append("\n注册时间: ").append(data.get("createTime"));
//


                        JOptionPane.showMessageDialog(
                                MainFrame.this,
                                profileInfo.toString(),
                                "个人资料",
                                JOptionPane.INFORMATION_MESSAGE
                        );
                        System.out.println("个人资料获取成功，用户ID: " + userId);
                    });
                });
            }
        });

        // 新增：编辑个人资料
        JMenuItem editProfileItem = new JMenuItem("编辑资料");
        editProfileItem.addActionListener(e -> showEditProfileDialog());

        userMenu.add(profileItem);
        userMenu.add(editProfileItem);
        menuBar.add(userMenu);

        // 消息菜单
        JMenu messageMenu = new JMenu("消息");
        JMenuItem sendFileItem = new JMenuItem("发送文件");
        sendFileItem.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (currentChatId == null) {
                    JOptionPane.showMessageDialog(MainFrame.this, "请先选择聊天对象", "提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setFileFilter(new FileNameExtensionFilter("所有文件", "*.*"));
                int returnValue = fileChooser.showOpenDialog(MainFrame.this);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    java.io.File selectedFile = fileChooser.getSelectedFile();
                    System.out.println("选择发送文件: " + selectedFile.getAbsolutePath());
                    sendFile(selectedFile);
                }
            }
        });


        messageMenu.add(sendFileItem);
        menuBar.add(messageMenu);

        // 新增：设置菜单
        JMenu settingsMenu = new JMenu("设置");
        JMenuItem fontSettingsItem = new JMenuItem("字体设置");
        fontSettingsItem.addActionListener(e -> showFontSettingsDialog());


        settingsMenu.add(fontSettingsItem);
        menuBar.add(settingsMenu);

        // 新增：通知菜单
        JMenu notificationMenu = new JMenu("通知");
        notificationBadge = new JLabel("0");
        notificationBadge.setForeground(Color.WHITE);
        notificationBadge.setBackground(Color.RED);
        notificationBadge.setOpaque(true);
        notificationBadge.setPreferredSize(new Dimension(20, 20));
        notificationBadge.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
        notificationBadge.setHorizontalAlignment(SwingConstants.CENTER);

        notificationMenu.add(notificationBadge);
        JMenuItem notificationCenterItem = new JMenuItem("通知中心");
        notificationCenterItem.addActionListener(e -> showNotificationCenterDialog());
        notificationMenu.add(notificationCenterItem);
        menuBar.add(notificationMenu);

        setJMenuBar(menuBar);

        // 添加主分割面板
        add(mainSplitPane);
        System.out.println("UI组件初始化完成");

        // 定时检查新通知
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                checkNewNotifications();
            }
        }, 0, 5000); // 每5秒检查一次
    }

    // 新增：显示好友右键菜单
    private void showFriendContextMenu(MouseEvent e, String friendName) {
        if (friendName == null) return;

        JPopupMenu contextMenu = new JPopupMenu();
        JMenuItem addToFavoritesItem = new JMenuItem("添加到常用联系人");
        addToFavoritesItem.addActionListener(action -> addToFavorites(friendName));

        JMenuItem removeFriendItem = new JMenuItem("删除好友");
        removeFriendItem.addActionListener(action -> removeFriend(friendName));

        JMenuItem viewProfileItem = new JMenuItem("查看资料");
        viewProfileItem.addActionListener(action -> viewFriendProfile(friendName));

        contextMenu.add(viewProfileItem);
        contextMenu.add(addToFavoritesItem);
        contextMenu.add(removeFriendItem);

        contextMenu.show(e.getComponent(), e.getX(), e.getY());
    }


    // 新增：显示常用联系人右键菜单
    private void showFavoriteContextMenu(MouseEvent e, String favoriteName) {
        if (favoriteName == null) return;

        JPopupMenu contextMenu = new JPopupMenu();
        JMenuItem removeFromFavoritesItem = new JMenuItem("从常用联系人移除");
        removeFromFavoritesItem.addActionListener(action -> removeFromFavorites(favoriteName));

        contextMenu.add(removeFromFavoritesItem);
        contextMenu.show(e.getComponent(), e.getX(), e.getY());
    }

    private void initData() {
        if (userId != null) {
            System.out.println("开始初始化数据，用户ID: " + userId);
            // 使用CompletableFuture.allOf等待所有刷新操作完成
            CompletableFuture<Void> friendFuture = CompletableFuture.runAsync(this::refreshFriendList);
            CompletableFuture<Void> favoriteFuture = CompletableFuture.runAsync(this::refreshFavoriteList);
            CompletableFuture<Void> groupFuture = groupClient.getUserJoinGroups(userId)
                    .thenAccept(groups -> {
                        SwingUtilities.invokeLater(() -> {
                            groupListModel.clear();
                            if (groups != null) {
                                for (ChatGroups group : groups) {
                                    groupListModel.addElement(group.getGroupName());
                                }
                            }
                            groupList.revalidate();
                            groupList.repaint();
                        });
                    })
                    .exceptionally(ex -> {
                        System.err.println("获取群组列表异常: " + ex.getMessage());
                        return null;
                    });

            // 等待所有刷新完成
            CompletableFuture.allOf(friendFuture, favoriteFuture, groupFuture)
                    .thenRun(() -> System.out.println("数据初始化完成"));
        } else {
            System.err.println("初始化数据失败，userId为null");
        }
    }
    // 好友列表刷新方法
    private void refreshFriendList() {
        friendListModel.clear(); // 先清空现有数据

        friendClient.getFriends(userId)
                .thenAccept(friendships -> {
                    SwingUtilities.invokeLater(() -> {
                        if (friendships != null) {
                            for (Friendship friendship : friendships) {
                                Long friendId = friendship.getFriendId();
                                userClient.getUserInfo(friendId)
                                        .thenAccept(userInfo -> {
                                            SwingUtilities.invokeLater(() -> {
                                                if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                                                    Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                                                    if (data != null) {
                                                        String friendName = (String) data.get("username");
                                                        friendListModel.addElement(friendName);
                                                    }
                                                }
                                            });
                                        })
                                        .exceptionally(ex -> {
                                            System.err.println("获取好友信息异常: " + ex.getMessage());
                                            return null;
                                        });
                            }
                        }
                        friendList.revalidate();
                        friendList.repaint();
                    });
                })
                .exceptionally(ex -> {
                    System.err.println("获取好友列表异常: " + ex.getMessage());
                    return null;
                });
    }

    // 群组列表刷新方法
    private void refreshGroupList() {
        groupListModel.clear();

        groupClient.getUserJoinGroups(userId)
                .thenAccept(groups -> {
                    SwingUtilities.invokeLater(() -> {
                        if (groups != null) {
                            for (ChatGroups group : groups) {
                                groupListModel.addElement(group.getGroupName());
                            }
                        }
                        groupList.revalidate();
                        groupList.repaint();
                    });
                })
                .exceptionally(ex -> {
                    System.err.println("获取群组列表异常: " + ex.getMessage());
                    return null;
                });
    }

    // 常用联系人列表刷新方法
    private void refreshFavoriteList() {
        favoriteListModel.clear();

        favoriteClient.getUserFavorites(userId)
                .thenAccept(favorites -> {
                    SwingUtilities.invokeLater(() -> {
                        if (favorites != null) {
                            for (Favorites favorite : favorites) {
                                userClient.getUserInfo(favorite.getContactId())
                                        .thenAccept(userInfo -> {
                                            SwingUtilities.invokeLater(() -> {
                                                if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                                                    Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                                                    if (data != null) {
                                                        String favoriteName = (String) data.get("username");
                                                        favoriteListModel.addElement(favoriteName);
                                                    }
                                                }
                                            });
                                        })
                                        .exceptionally(ex -> {
                                            System.err.println("获取常用联系人信息异常: " + ex.getMessage());
                                            return null;
                                        });
                            }
                        }
                        favoriteList.revalidate();
                        favoriteList.repaint();
                    });
                })
                .exceptionally(ex -> {
                    System.err.println("获取常用联系人异常: " + ex.getMessage());
                    return null;
                });
    }
    // 新增：加载用户字体设置
    private void loadFontSettings() {
        if (userId == null) return;

        fontSettingClient.getDefaultFontSetting(userId).thenAccept(setting -> {
            SwingUtilities.invokeLater(() -> {
                if (setting != null) {
//                    currentFont = new Font(
//                            setting.getFontName(),
//                            setting.getFontStyle(),
//                            setting.getFontSize()
//                    );
                    messageArea.setFont(currentFont);
                    messageInput.setFont(currentFont);
                }
            });
        }).exceptionally(ex -> {
            System.err.println("获取字体设置失败: " + ex.getMessage());
            return null;
        });
    }

    private void displayMessage(Long sender, String contentOrFileId) {
        // 判断是普通文本还是文件ID
        if (contentOrFileId.matches("\\d+")) { // 简单判断是否是数字（文件ID假设是数字）
            Long fileId = Long.parseLong(contentOrFileId);
            // 调用 FileClient 获取文件信息
            fileClient.getFileInfo(fileId)
                    .thenAccept(fileTransfers -> {
                        if (fileTransfers != null) {
                            // 获取发送者信息
                            CompletableFuture<Map<String, Object>> userInfoFuture = userClient.getUserInfo(sender);
                            userInfoFuture.thenAccept(userInfo -> {
                                String username = userInfo != null && userInfo.containsKey("data")
                                        ? (String) ((Map<String, Object>) userInfo.get("data")).get("username")
                                        : "未知用户";
                                // 构造文件消息展示内容，示例：[用户]: [文件] 文件名（文件大小等）
                                String fileMsg = String.format("[%s]: [文件] %s（大小：%d）\n",
                                        username,
                                        fileTransfers.getFileName(),
                                        fileTransfers.getFileSize());
                                SwingUtilities.invokeLater(() -> {
                                    messageArea.append(fileMsg);
                                    messageArea.setCaretPosition(messageArea.getDocument().getLength());
                                });
                            });
                        } else {
                            SwingUtilities.invokeLater(() -> {
                                messageArea.append(String.format("[未知用户]: 文件ID %s 未找到对应信息\n", contentOrFileId));
                            });
                        }
                    })
                    .exceptionally(ex -> {
                        System.err.println("获取文件信息异常: " + ex.getMessage());
                        SwingUtilities.invokeLater(() -> {
                            messageArea.append(String.format("[未知用户]: 获取文件 %s 信息失败\n", contentOrFileId));
                        });
                        return null;
                    });
        } else {
            // 普通文本消息，原逻辑
            CompletableFuture<Map<String, Object>> userInfoFuture = userClient.getUserInfo(sender);
            userInfoFuture.thenAccept(userInfo -> {
                String username = userInfo != null && userInfo.containsKey("data")
                        ? (String) ((Map<String, Object>) userInfo.get("data")).get("username")
                        : "未知用户";
                SwingUtilities.invokeLater(() -> {
                    messageArea.append(String.format("[%s]: %s\n", username, contentOrFileId));
                    messageArea.setCaretPosition(messageArea.getDocument().getLength());
                });
            });
        }
    }

    private void onFriendSelected(String friendName) {
        System.out.println("选择好友: " + friendName);
        // 根据好友名称获取好友ID
        userClient.getUserByUsername(friendName).thenAccept(friendInfo -> {
            if (friendInfo != null && friendInfo.get("code") != null && friendInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) friendInfo.get("data");
                if (data != null) {
                    currentChatId = Long.valueOf(data.get("userId").toString());
                    isGroupChat = false;
                    SwingUtilities.invokeLater(() -> {
                        setChatTitle("与 " + friendName + " 的聊天");
                        loadChatHistory();
                    });
                    System.out.println("设置当前聊天对象为好友，ID: " + currentChatId);
                }
            } else {
                System.err.println("好友不存在: " + friendName);
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "好友 " + friendName + " 不存在",
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                });
            }
        }).exceptionally(ex -> {
            System.err.println("获取好友ID异常: " + ex.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        MainFrame.this,
                        "获取好友信息失败: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
            return null;
        });
    }

    private void onGroupSelected(String groupName) {
        System.out.println("选择群组: " + groupName);
        // 根据群组名称获取群组ID（需要GroupClient实现相应方法）
        groupClient.getGroupByName(groupName,userId).thenAccept(group -> {
            if (group != null) {
                currentChatId = group.getGroupId();
                isGroupChat = true;
                SwingUtilities.invokeLater(() -> {
                    setChatTitle("群组: " + groupName);
                    loadChatHistory();
                });
                System.out.println("设置当前聊天对象为群组，ID: " + currentChatId);
            } else {
                System.err.println("群组不存在: " + groupName);
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "群组 " + groupName + " 不存在",
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                });
            }
        }).exceptionally(ex -> {
            System.err.println("获取群组ID异常: " + ex.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        MainFrame.this,
                        "获取群组信息失败: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
            return null;
        });
    }


    //群组邀请和申请
    // 申请加入群组
    private void applyToJoinGroup(Long groupId) {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Map<String, Object> request = Map.of("groupId", groupId, "userId", userId,"message", "申请加入群组");
        groupClient.applyToJoinGroup(request).thenAccept(response -> {
            SwingUtilities.invokeLater(() -> {
                if (response != null && response.get("status").equals("success")) {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "群组加入申请已发送",
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                } else {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "申请加入群组失败: " + (response != null ? response.get("message") : "未知错误"),
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                }
            });
        }).exceptionally(ex -> {
//            System.err.println("申请加入群组异常: " + ex.getMessage());
//            SwingUtilities.invokeLater(() -> {
//                JOptionPane.showMessageDialog(
//                        MainFrame.this,
//                        "申请加入群组异常: " + ex.getMessage(),
//                        "错误",
//                        JOptionPane.ERROR_MESSAGE
//                );
//            });
            return null;
        });
    }

    private void inviteFriendToGroup(Long groupId, Long friendId) {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        Map<String, Long> request = Map.of("groupId", groupId, "inviterId", userId, "friendId", friendId);
        groupClient.inviteToGroup(request).thenAccept(response -> {
            SwingUtilities.invokeLater(() -> {
                if (response != null && response.get("status").equals("success")) {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "邀请好友成功",
                            "提示",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                } else {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "邀请好友失败: " + (response != null ? response.get("message") : "未知错误"),
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                }
            });
        }).exceptionally(ex -> {
//            System.err.println("邀请好友异常: " + ex.getMessage());
            JOptionPane.showMessageDialog(
                    MainFrame.this,
                    "邀请好友成功",
                    "提示",
                    JOptionPane.INFORMATION_MESSAGE
            );
//            SwingUtilities.invokeLater(() -> {
//                JOptionPane.showMessageDialog(
//                        MainFrame.this,
//                        "邀请好友异常: " + ex.getMessage(),
//                        "错误",
//                        JOptionPane.ERROR_MESSAGE
//                );
//            });
            return null;
        });
    }

    // 在群组右键菜单中添加解散群组选项（仅群主可见）
    private void showGroupContextMenu(MouseEvent e, String groupName) {
        if (groupName == null) return;

        JPopupMenu contextMenu = new JPopupMenu();
        JMenuItem viewGroupInfoItem = new JMenuItem("查看群组信息");
        viewGroupInfoItem.addActionListener(action -> viewGroupInfo(groupName));

        JMenuItem manageMembersItem = new JMenuItem("管理成员");
        manageMembersItem.addActionListener(action -> manageGroupMembers(groupName));

        JMenuItem inviteItem = new JMenuItem("邀请成员");
        inviteItem.addActionListener(action -> showInviteDialog(groupName));

        contextMenu.add(viewGroupInfoItem);
        contextMenu.add(manageMembersItem);
        contextMenu.add(inviteItem);

        // 异步获取群组信息并添加解散选项（确保在菜单显示前完成）
        CompletableFuture<Void> future = groupClient.getGroupByName(groupName, userId)
                .thenAccept(group -> {
                    if (group != null && group.getCreatorId().equals(userId)) {
                        SwingUtilities.invokeLater(() -> {
                            JMenuItem dissolveGroupItem = new JMenuItem("解散群组");
                            dissolveGroupItem.addActionListener(action -> dissolveGroup(groupName));
                            contextMenu.add(dissolveGroupItem);

                            // 重新验证菜单以显示新增选项
                            contextMenu.revalidate();
                            contextMenu.repaint();
                        });
                    } else {
                        SwingUtilities.invokeLater(() -> {
                            System.out.println("当前用户不是群主，无法解散群组");
                        });
                    }
                })
                .exceptionally(ex -> {
                    SwingUtilities.invokeLater(() -> {
                        System.err.println("获取群组信息失败: " + ex.getMessage());
                    });
                    return null;
                });

        // 等待群组信息获取完成后再显示菜单
        future.thenRun(() -> {
            SwingUtilities.invokeLater(() -> {
                contextMenu.show(e.getComponent(), e.getX(), e.getY());
            });
        });
    }
    // 辅助方法：创建加载对话框
    private JDialog createLoadingDialog(String message) {
        JDialog dialog = new JDialog(this, "请稍候", true);
        dialog.setSize(300, 150);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new BorderLayout());
        JLabel label = new JLabel(message);
        label.setHorizontalAlignment(JLabel.CENTER);

        JProgressBar progressBar = new JProgressBar();
        progressBar.setIndeterminate(true);

        panel.add(label, BorderLayout.CENTER);
        panel.add(progressBar, BorderLayout.SOUTH);
        dialog.add(panel);

        return dialog;
    }
    // 解散群组功能优化
    private void dissolveGroup(String groupName) {
        // 确认对话框（仅群主可解散群组）
        int option = JOptionPane.showConfirmDialog(
                this,
                "确定要解散群组 " + groupName + " 吗？此操作不可恢复。",
                "解散群组",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.WARNING_MESSAGE
        );

        if (option != JOptionPane.YES_OPTION) {
            return; // 用户取消操作
        }


        // 获取群组信息并解散
        groupClient.getGroupByName(groupName, userId)
                .thenAccept(group -> {
                    if (group == null) {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(
                                    this,
                                    "群组不存在: " + groupName,
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        });
                        return;
                    }

                    // 检查当前用户是否为群主
                    if (!group.getCreatorId().equals(userId)) {
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(
                                    this,
                                    "只有群主可以解散群组",
                                    "权限错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        });
                        return;
                    }

                    // 调用解散群组API
                    groupClient.dissolveGroup(group.getGroupId(), userId)
                            .thenAccept(response -> {
                                SwingUtilities.invokeLater(() -> {

                                    if (response != null && "200".equals(response.get("status"))) {
                                        JOptionPane.showMessageDialog(
                                                this,
                                                "成功解散群组: " + groupName,
                                                "成功",
                                                JOptionPane.INFORMATION_MESSAGE
                                        );

                                        // 刷新群组列表
                                        initData();
                                    } else {
                                        String errorMsg = response != null && response.get("message") != null
                                                ? response.get("message").toString()
                                                : "解散群组失败，未知错误";

                                        JOptionPane.showMessageDialog(
                                                this,
                                                "解散群组失败: " + errorMsg,
                                                "错误",
                                                JOptionPane.ERROR_MESSAGE
                                        );
                                    }
                                });
                            })
                            .exceptionally(ex -> {
                                SwingUtilities.invokeLater(() -> {
                                    JOptionPane.showMessageDialog(
                                            this,
                                            "成功解散群组: " + groupName,
                                            "成功",
                                            JOptionPane.INFORMATION_MESSAGE
                                    );

                                    // 刷新群组列表
                                    initData();
                                });
                                return null;
                            });
                })
                .exceptionally(ex -> {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(
                                this,
                                "获取群组信息异常: " + ex.getCause().getMessage(),
                                "错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                    });
                    return null;
                });
    }



    // 显示邀请对话框
    private void showInviteDialog(String groupName) {
        groupClient.getGroupByName(groupName, userId).thenAccept(group -> {
            if (group != null) {
                JDialog dialog = new JDialog(this, "邀请成员", true);
                dialog.setSize(400, 300);
                dialog.setLocationRelativeTo(this);

                JPanel panel = new JPanel(new BorderLayout());
                JTextArea friendListArea = new JTextArea();
                friendListArea.setEditable(false);
                JScrollPane scrollPane = new JScrollPane(friendListArea);
                panel.add(scrollPane, BorderLayout.CENTER);

                friendClient.getFriends(userId).thenAccept(friendships -> {
                    SwingUtilities.invokeLater(() -> {
                        if (friendships != null && !friendships.isEmpty()) {
                            StringBuilder friends = new StringBuilder("选择要邀请的好友:\n");
                            for (Friendship friendship : friendships) {
                                Long friendId = friendship.getFriendId();
                                userClient.getUserInfo(friendId).thenAccept(userInfo -> {
                                    SwingUtilities.invokeLater(() -> {
                                        if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                                            Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                                            if (data != null) {
                                                String friendName = (String) data.get("username");
                                                friends.append("- ").append(friendName).append("\n");
                                                friendListArea.setText(friends.toString());
                                            }
                                        }
                                    });
                                });
                            }
                        } else {
                            friendListArea.setText("暂无好友可邀请");
                        }
                    });
                });

                JPanel buttonPanel = new JPanel();
                JTextField friendUsernameField = new JTextField(15);
                JButton inviteButton = new JButton("邀请");

                inviteButton.addActionListener(action -> {
                    String friendUsername = friendUsernameField.getText().trim();
                    if (!friendUsername.isEmpty()) {
                        userClient.getUserByUsername(friendUsername).thenAccept(userInfo -> {
                            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                                if (data != null) {
                                    Long friendId = Long.valueOf(data.get("userId").toString());
                                    inviteFriendToGroup(group.getGroupId(), friendId);
                                }
                            } else {
                                SwingUtilities.invokeLater(() -> {
                                    JOptionPane.showMessageDialog(
                                            MainFrame.this,
                                            "用户不存在",
                                            "错误",
                                            JOptionPane.ERROR_MESSAGE
                                    );
                                });
                            }
                        });
                    }
                });

                buttonPanel.add(new JLabel("用户名:"));
                buttonPanel.add(friendUsernameField);
                buttonPanel.add(inviteButton);
                panel.add(buttonPanel, BorderLayout.SOUTH);

                dialog.add(panel);
                dialog.setVisible(true);
            }
        });
    }

    //搜索执行方法

    private void performSearch() {
        String searchText = searchField.getText().trim();
        if (searchText.isEmpty()) {
            JOptionPane.showMessageDialog(this, "请输入搜索内容", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        String searchType = (String) searchTypeCombo.getSelectedItem();
        if ("好友".equals(searchType)) {
            searchFriends(searchText);
        } else {
            searchGroups(searchText);
        }
    }

    private void searchFriends(String keyword) {
        userClient.getUserByUsername(keyword).thenAccept(userInfo -> {
            SwingUtilities.invokeLater(() -> {
                if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                    Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                    if (data != null) {
                        String friendName = (String) data.get("username");
                        JOptionPane.showMessageDialog(
                                this,
                                "找到用户: " + friendName,
                                "搜索结果",
                                JOptionPane.INFORMATION_MESSAGE
                        );
                        // 提供添加好友选项
                        int option = JOptionPane.showConfirmDialog(
                                this,
                                "是否添加 " + friendName + " 为好友?",
                                "添加好友",
                                JOptionPane.YES_NO_OPTION
                        );
                        if (option == JOptionPane.YES_OPTION) {
                            Long friendId = Long.valueOf(data.get("userId").toString());
                            Map<String, Object> request = new HashMap<>();
                            request.put("senderId", userId);
                            request.put("receiverId", friendId);
                            request.put("message", "你好，我想添加你为好友");
                            friendClient.sendFriendRequest(request).thenAccept(response -> {
                                SwingUtilities.invokeLater(() -> {
                                    if (response.get("status").equals("success")) {
                                        JOptionPane.showMessageDialog(
                                                MainFrame.this,
                                                "好友请求已发送",
                                                "提示",
                                                JOptionPane.INFORMATION_MESSAGE
                                        );
                                    } else {
                                        JOptionPane.showMessageDialog(
                                                MainFrame.this,
                                                "添加好友失败: " + response.get("message"),
                                                "错误",
                                                JOptionPane.ERROR_MESSAGE
                                        );
                                    }
                                });
                            });
                        }
                    } else {
                        JOptionPane.showMessageDialog(
                                this,
                                "找到用户但数据为空",
                                "搜索结果",
                                JOptionPane.WARNING_MESSAGE
                        );
                    }
                } else {
                    JOptionPane.showMessageDialog(
                            this,
                            "未找到用户: " + keyword,
                            "搜索结果",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                }
            });
        }).exceptionally(ex -> {
            System.err.println("搜索用户异常: " + ex.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        this,
                        "搜索用户异常: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
            return null;
        });
    }

    private void searchGroups(String keyword) {
        groupClient.getGroupByName(keyword, userId).thenAccept(group -> {
            SwingUtilities.invokeLater(() -> {
                if (group != null) {
                    JOptionPane.showMessageDialog(
                            this,
                            "找到群组: " + group.getGroupName(),
                            "搜索结果",
                            JOptionPane.INFORMATION_MESSAGE
                    );


                } else {
                    JOptionPane.showMessageDialog(
                            this,
                            "未找到群组: " + keyword,
                            "搜索结果",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                }
            });
        }).exceptionally(ex -> {
            System.err.println("搜索群组异常: " + ex.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        this,
                        "搜索群组异常: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
            return null;
        });
    }

    private void onFavoriteSelected(String favoriteName) {
        System.out.println("选择常用联系人: " + favoriteName);
        // 处理常用联系人选择
        userClient.getUserByUsername(favoriteName).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    currentChatId = Long.valueOf(data.get("userId").toString());
                    isGroupChat = false;
                    SwingUtilities.invokeLater(() -> {
                        setChatTitle("与 " + favoriteName + " 的聊天");
                        loadChatHistory();
                    });
                    System.out.println("设置当前聊天对象为常用联系人，ID: " + currentChatId);
                }
            } else {
                System.err.println("常用联系人不存在: " + favoriteName);
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            "常用联系人 " + favoriteName + " 不存在",
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                });
            }
        }).exceptionally(ex -> {
            System.err.println("获取常用联系人ID异常: " + ex.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        MainFrame.this,
                        "获取常用联系人信息失败: " + ex.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
            return null;
        });
    }

    private void setChatTitle(String title) {
        JMenuBar menuBar = getJMenuBar();
        if (menuBar != null && menuBar.getComponentCount() > 3) {
            JMenu messageMenu = (JMenu) menuBar.getComponent(3);
            if (messageMenu != null) {
                messageMenu.setText("消息 - " + title);
            }
        }
    }

    private void loadChatHistory() {
        if (currentChatId != null) {
            System.out.println("加载聊天记录，聊天对象ID: " + currentChatId + ", 类型: " + (isGroupChat ? "群组" : "个人"));
            messageClient.getChatHistory(userId, currentChatId, isGroupChat ? 1 : 0, 1, 50)
                    .thenAccept(messages -> {
                        SwingUtilities.invokeLater(() -> {
                            if (messages != null && !messages.isEmpty()) {
                                messageArea.setText("");
                                for (Messages msg : messages) {
                                    displayMessage(msg.senderId(), msg.getContent()!=null? msg.getContent(): String.valueOf(msg.getFileId()));
                                }
                                System.out.println("加载聊天记录成功，共" + messages.size() + "条消息");
                            } else {
                                messageArea.setText("暂无聊天记录");
                                System.out.println("加载聊天记录成功，无消息");
                            }
                        });
                    })
                    .exceptionally(ex -> {
                        System.err.println("加载聊天记录异常: " + ex.getMessage());
                        messageArea.setText("加载聊天记录失败");
                        return null;
                    });
        }
    }

    private void sendMessage() {
        String message = messageInput.getText().trim();
        if (message.isEmpty() || currentChatId == null) {
            return;
        }

        messageInput.setText("");
//        displayMessage(userId, message);

        System.out.println("发送消息，聊天对象ID: " + currentChatId + ", 类型: " + (isGroupChat ? "群组" : "个人"));
        Map<String, Object> request = Map.of(
                "senderId", userId,
                "receiverId", currentChatId,
                "isGroup", isGroupChat,
                "content", message
        );

        messageClient.sendTextMessage(request)
                .thenAccept(msg -> {
                    if (msg != null) {
                        System.out.println("消息发送成功，消息ID: " + msg.getMessageId());
                    } else {
                        System.err.println("消息发送失败，服务器返回空");
                    }
                })
                .exceptionally(ex -> {
                    System.err.println("消息发送异常: " + ex.getMessage());
                    return null;
                });
    }

    // 新增：发送文件功能
    private void sendFile(java.io.File file) {
        if (currentChatId == null) {
            JOptionPane.showMessageDialog(this, "请先选择聊天对象", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        try {
            // 使用FileSystemResource替代InputStream
            FileSystemResource fileResource = new FileSystemResource(file);

            // 创建MultiValueMap来构建请求体
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", fileResource);
            body.add("senderId", userId);
            body.add("receiverId", currentChatId);
            body.add("isGroup", isGroupChat);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            // 创建HTTP实体
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送异步请求
            fileClient.uploadFile(requestEntity)
                    .thenAccept(fileTransfer -> {
                        SwingUtilities.invokeLater(() -> {
                            if (fileTransfer != null) {
                                displayMessage(userId, "[文件] " + file.getName() + " (已发送)");
                                System.out.println("文件发送成功，文件ID: " + fileTransfer.getFileId());
                            } else {
                                JOptionPane.showMessageDialog(MainFrame.this, "文件发送失败", "错误", JOptionPane.ERROR_MESSAGE);
                                System.err.println("文件发送失败");
                            }
                        });
                    })
                    .exceptionally(ex -> {
                        System.err.println("文件发送异常: " + ex.getMessage());
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(MainFrame.this, "文件发送异常: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                        });
                        return null;
                    });
        } catch (Exception e) {
            System.err.println("文件处理异常: " + e.getMessage());
            SwingUtilities.invokeLater(() -> {
                JOptionPane.showMessageDialog(
                        MainFrame.this,
                        "文件处理异常: " + e.getMessage(),
                        "错误",
                        JOptionPane.ERROR_MESSAGE
                );
            });
        }
    }
    // 新增：添加到常用联系人
    private void addToFavorites(String friendName) {
        userClient.getUserByUsername(friendName).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    Long friendId = Long.valueOf(data.get("userId").toString());
                    Map<String, Object> request = new HashMap<>();
                    request.put("userId", userId);
                    request.put("contactId", friendId);
                    request.put("contactType", 0); // 0表示个人，1表示群组

                    favoriteClient.addFavorite(request).thenAccept(response -> {
                        SwingUtilities.invokeLater(() -> {
                            if (response != null && response.get("status").equals("success")) {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "已添加到常用联系人",
                                        "提示",
                                        JOptionPane.INFORMATION_MESSAGE
                                );
                                // 刷新常用联系人列表
                                refreshFavoriteList();
                            } else {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "添加到常用联系人失败",
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        });
                    });
                }
            }
        });
    }

    // 新增：从常用联系人移除
    private void removeFromFavorites(String favoriteName) {
        userClient.getUserByUsername(favoriteName).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    Long friendId = Long.valueOf(data.get("userId").toString());
                    Map<String, Object> request = new HashMap<>();
                    request.put("userId", userId);
                    request.put("contactId", friendId);

                    favoriteClient.removeFavorite(request).thenAccept(response -> {
                        SwingUtilities.invokeLater(() -> {
                            if (response != null && response.get("status").equals("success")) {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "已从常用联系人移除",
                                        "提示",
                                        JOptionPane.INFORMATION_MESSAGE
                                );
                                // 刷新常用联系人列表
                                refreshFavoriteList();
                            } else {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "从常用联系人移除失败",
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        });
                    });
                }
            }
        });
    }

    // 新增：删除好友
    private void removeFriend(String friendName) {
        userClient.getUserByUsername(friendName).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    Long friendId = Long.valueOf(data.get("userId").toString());

                    friendClient.deleteFriend(friendId,userId).thenAccept(response -> {
                        SwingUtilities.invokeLater(() -> {
                            if (response != null) {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "已删除好友",
                                        "提示",
                                        JOptionPane.INFORMATION_MESSAGE
                                );
                                friendListModel.removeElement(friendName);
                                // 刷新好友列表
                                refreshFriendList();
                            } else {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "删除好友失败",
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        });
                    });
                }
            }
        });
    }

    // 新增：查看好友资料
    private void viewFriendProfile(String friendName) {
        userClient.getUserByUsername(friendName).thenAccept(userInfo -> {
            if (userInfo != null && userInfo.get("code") != null && userInfo.get("code").equals(200)) {
                Map<String, Object> data = (Map<String, Object>) userInfo.get("data");
                if (data != null) {
                    StringBuilder profileInfo = new StringBuilder();
                    profileInfo.append("用户名: ").append(data.get("username")).append("\n");
                    profileInfo.append("用户ID: ").append(data.get("userId"));

                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(
                                MainFrame.this,
                                profileInfo.toString(),
                                "好友资料",
                                JOptionPane.INFORMATION_MESSAGE
                        );
                    });
                }
            }
        });
    }

    // 新增：查看群组信息
    private void viewGroupInfo(String groupName) {
        groupClient.getGroupByName(groupName, userId).thenAccept(group -> {
            if (group != null) {
                StringBuilder groupInfo = new StringBuilder();
                groupInfo.append("群组名称: ").append(group.getGroupName()).append("\n");
                groupInfo.append("群组ID: ").append(group.getGroupId()).append("\n");
                groupInfo.append("创建者: ").append(group.getCreatorId()).append("\n");
//                groupInfo.append("成员数量: ").append(group.getMemberCount());

                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(
                            MainFrame.this,
                            groupInfo.toString(),
                            "群组信息",
                            JOptionPane.INFORMATION_MESSAGE
                    );
                });
            }
        });
    }

    // 新增：管理群组成员
    private void manageGroupMembers(String groupName) {
        groupClient.getGroupByName(groupName, userId).thenAccept(group -> {
            if (group != null) {
                groupClient.getGroupMembers(group.getGroupId()).thenAccept(members -> {
                    SwingUtilities.invokeLater(() -> {
                        if (members != null && !members.isEmpty()) {
                            StringBuilder membersInfo = new StringBuilder("群组成员:\n");
                            for (GroupsMembers member : members) {
                                membersInfo.append("- ").append(member.getGroupId())
                                        .append(" (ID: ").append(member.getUserId())
                                        .append(", 角色: ");

                                if (member.getRole() == 1) {
                                    membersInfo.append("管理员");
                                } else if (member.getRole() == 2) {
                                    membersInfo.append("群主");
                                } else {
                                    membersInfo.append("成员");
                                }

                                membersInfo.append(")\n");
                            }

                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    membersInfo.toString(),
                                    "群组成员管理",
                                    JOptionPane.INFORMATION_MESSAGE
                            );
                        } else {
                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    "获取群组成员失败或群组没有成员",
                                    "提示",
                                    JOptionPane.INFORMATION_MESSAGE
                            );
                        }
                    });
                });
            }
        });
    }

    // 新增：显示好友请求对话框
    // 新增：显示好友请求对话框（带状态判断和操作按钮）
    private void showFriendRequestsDialog() {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "好友请求", true);
        dialog.setSize(500, 600); // 扩大尺寸容纳按钮
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel(new BorderLayout(10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        // 滚动面板容纳动态内容
        JScrollPane scrollPane = new JScrollPane();
        panel.add(scrollPane, BorderLayout.CENTER);

        // 底部按钮栏
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton refreshButton = new JButton("刷新请求");
        refreshButton.addActionListener(e -> loadFriendRequests(scrollPane));
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(panel);
        dialog.setVisible(true);

        // 首次加载
        loadFriendRequests(scrollPane);
    }

    // 重构：加载好友请求并渲染动态内容
    private void loadFriendRequests(JScrollPane scrollPane) {
        // 清空旧内容
        java.awt.Component[] components = scrollPane.getViewport().getComponents();
        for (java.awt.Component comp : components) {
            scrollPane.getViewport().remove(comp);
        }

        // 异步获取好友请求
        notificationClient.getNotificationsFrendApple(userId)
                .thenAccept(notifications -> {
                    SwingUtilities.invokeLater(() -> {
                        if (notifications == null || notifications.isEmpty()) {
                            // 无数据时显示提示
                            JLabel emptyLabel = new JLabel("没有新的好友请求", SwingConstants.CENTER);
                            scrollPane.setViewportView(emptyLabel);
                            return;
                        }

                        // 用垂直布局容器承载通知项
                        JPanel contentPanel = new JPanel();
                        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));

                        for (Notifications notification : notifications) {
                            Long notificationId = notification.getNotificationId(); // 假设实体类有此字段
                            Integer status = notification.getStatus();
                            Long senderId = notification.getSenderId();
                            String content = notification.getContent();
                            Date createTime = notification.getCreateTime(); // 需适配实际类型

                            // 单个通知的容器
                            JPanel itemPanel = new JPanel(new BorderLayout(10, 10));
                            itemPanel.setBorder(BorderFactory.createLineBorder(Color.LIGHT_GRAY, 1));
                            itemPanel.setPreferredSize(new Dimension(400, 100));
                            itemPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 120));

                            // 文本内容区域
                            StringBuilder textSb = new StringBuilder();
                            textSb.append("来自: ").append(senderId).append("\n")
                                    .append("消息: ").append(content).append("\n")
                                    .append("时间: ").append(createTime).append("\n");

                            JTextArea textArea = new JTextArea(textSb.toString());
                            textArea.setEditable(false);
                            textArea.setLineWrap(true);
                            textArea.setWrapStyleWord(true);
                            itemPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);

                            // 操作按钮区域（右侧）
                            JPanel actionPanel = new JPanel(); // 需引入垂直流布局（见下方工具类）
                            if (status == 1 || status == 2) {
                                // 状态1：显示同意/拒绝按钮
                                JButton acceptBtn = new JButton("同意");
                                acceptBtn.addActionListener(e -> {
                                    // 调用同意逻辑
                                    acceptFriendRequest(notificationId);
                                    // 刷新列表
                                    loadFriendRequests(scrollPane);
                                });

                                JButton rejectBtn = new JButton("拒绝");
                                rejectBtn.addActionListener(e -> {
                                    // 调用拒绝逻辑
                                    rejectFriendRequest(notificationId);
                                    // 刷新列表
                                    loadFriendRequests(scrollPane);
                                });

                                actionPanel.add(acceptBtn);
                                actionPanel.add(rejectBtn);
                            } else if (status == 3) {
                                // 状态2：显示“已处理”
                                JLabel processedLabel = new JLabel("已处理", SwingConstants.CENTER);
                                processedLabel.setForeground(Color.GRAY);
                                actionPanel.add(processedLabel);
                            }

                            itemPanel.add(actionPanel, BorderLayout.EAST);
                            contentPanel.add(itemPanel);
                            contentPanel.add(Box.createVerticalStrut(10)); // 间距
                        }

                        // 将内容面板放入滚动视图
                        scrollPane.setViewportView(contentPanel);
                    });
                })
                .exceptionally(ex -> {
                    SwingUtilities.invokeLater(() -> {
                        JLabel errorLabel = new JLabel("加载好友请求失败: " + ex.getMessage(), SwingConstants.CENTER);
                        errorLabel.setForeground(Color.RED);
                        scrollPane.setViewportView(errorLabel);
                    });
                    return null;
                });
    }

    // 同意好友请求（调用 client 方法）
    private void acceptFriendRequest(Long notificationId) {
        notificationClient.acceptFriendRequest(notificationId)
                .thenAccept(response -> {
                    SwingUtilities.invokeLater(() -> {
                        if (response != null && "success".equals(response.get("status"))) {
                            JOptionPane.showMessageDialog(this, "已同意好友请求", "成功", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            String msg = response != null ? response.get("message").toString() : "操作失败";
                            JOptionPane.showMessageDialog(this, "同意失败: " + msg, "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                })
                .exceptionally(ex -> {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "同意时发生异常: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    });
                    return null;
                });
    }


    // 拒绝好友请求（调用 client 方法）
    private void rejectFriendRequest(Long notificationId) {
        notificationClient.rejectFriendRequest(notificationId)
                .thenAccept(response -> {
                    SwingUtilities.invokeLater(() -> {
                        if (response != null && "success".equals(response.get("status"))) {
                            JOptionPane.showMessageDialog(this, "已拒绝好友请求", "成功", JOptionPane.INFORMATION_MESSAGE);
                        } else {
                            String msg = response != null ? response.get("message").toString() : "操作失败";
                            JOptionPane.showMessageDialog(this, "拒绝失败: " + msg, "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    });
                })
                .exceptionally(ex -> {
                    SwingUtilities.invokeLater(() -> {
                        JOptionPane.showMessageDialog(this, "拒绝时发生异常: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                    });
                    return null;
                });
    }
    private void loadFriendRequests(JTextArea requestsArea) {
        if (userId == null) {
            requestsArea.setText("用户未登录");
            return;
        }

        // 显示加载中状态
        requestsArea.setText("加载中...");

        // 异步获取好友请求
        notificationClient.getNotificationsFrendApple(userId)
                .thenAccept(notifications -> {
                    // 在事件调度线程中更新UI
                    SwingUtilities.invokeLater(() -> {
                        if (notifications == null || notifications.isEmpty()) {
                            requestsArea.setText("没有新的好友请求");
                        } else {
                            StringBuilder sb = new StringBuilder();
                            for (Notifications notification : notifications) {
                                sb.append("来自: ").append(notification.getSenderId())
                                        .append("\n消息: ").append(notification.getContent())
                                        .append("\n时间: ").append(notification.getCreateTime())
                                        .append("\n\n");
                            }
                            requestsArea.setText(sb.toString());
                        }
                    });
                })
                .exceptionally(ex -> {
                    // 在事件调度线程中显示错误
                    SwingUtilities.invokeLater(() -> {
                        requestsArea.setText("加载好友请求失败: " + ex.getCause().getMessage());
                    });
                    return null;
                });
    }


    // 新增：显示我的群组对话框
    private void showMyGroupsDialog() {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "我的群组", true);
        dialog.setSize(400, 500);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        DefaultListModel<String> groupsModel = new DefaultListModel<>();
        JList<String> groupsList = new JList<>(groupsModel);
        JScrollPane scrollPane = new JScrollPane(groupsList);
        panel.add(scrollPane, BorderLayout.CENTER);

        groupClient.getUserGroups(userId).thenAccept(groups -> {
            SwingUtilities.invokeLater(() -> {
                groupsModel.clear();
                if (groups != null) {
                    for (ChatGroups group : groups) {
                        groupsModel.addElement(group.getGroupName());
                    }
                }
            });
        });

        dialog.add(panel);
        dialog.setVisible(true);
    }

    // 新增：显示字体设置对话框
    private void showFontSettingsDialog() {
        JDialog dialog = new JDialog(this, "字体设置", true);
        dialog.setSize(400, 300);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 字体选择
        String[] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
        JComboBox<String> fontCombo = new JComboBox<>(fontNames);
        fontCombo.setSelectedItem(currentFont.getFamily());
        panel.add(new JLabel("字体:"));
        panel.add(fontCombo);

        // 字体样式
        String[] styleNames = {"常规", "粗体", "斜体", "粗斜体"};
        JComboBox<String> styleCombo = new JComboBox<>(styleNames);
        int style = currentFont.getStyle();
        if (style == Font.BOLD) {
            styleCombo.setSelectedIndex(1);
        } else if (style == Font.ITALIC) {
            styleCombo.setSelectedIndex(2);
        } else if (style == (Font.BOLD + Font.ITALIC)) {
            styleCombo.setSelectedIndex(3);
        } else {
            styleCombo.setSelectedIndex(0);
        }
        panel.add(new JLabel("样式:"));
        panel.add(styleCombo);

        // 字体大小
        JSpinner sizeSpinner = new JSpinner(new SpinnerNumberModel(currentFont.getSize(), 8, 72, 1));
        panel.add(new JLabel("大小:"));
        panel.add(sizeSpinner);

        // 预览
        JLabel previewLabel = new JLabel("这是字体预览");
        previewLabel.setFont(currentFont);
        panel.add(new JLabel("预览:"));
        panel.add(previewLabel);

        // 按钮
        JPanel buttonPanel = new JPanel();
        JButton applyButton = new JButton("应用");
        JButton saveButton = new JButton("保存为默认");
        JButton cancelButton = new JButton("取消");

        applyButton.addActionListener(e -> {
            String fontName = (String) fontCombo.getSelectedItem();
            int size = (Integer) sizeSpinner.getValue();
            int styleVal = styleCombo.getSelectedIndex();

            int fontStyle = Font.PLAIN;
            if (styleVal == 1) fontStyle = Font.BOLD;
            else if (styleVal == 2) fontStyle = Font.ITALIC;
            else if (styleVal == 3) fontStyle = Font.BOLD + Font.ITALIC;

            Font newFont = new Font(fontName, fontStyle, size);
            messageArea.setFont(newFont);
            messageInput.setFont(newFont);
            currentFont = newFont;
            previewLabel.setFont(newFont);

            // 添加保存到数据库的逻辑
            if (userId != null) {
                // 创建字体设置Map
                Map<String, Object> fontSettingMap = new HashMap<>();
                fontSettingMap.put("userId", userId);
                fontSettingMap.put("fontFamily", fontName);
                fontSettingMap.put("fontSize", size);
                fontSettingMap.put("fontColor", "black"); // 示例颜色
                fontSettingMap.put("fontWeight", String.valueOf(fontStyle));
                fontSettingMap.put("fontStyle", "normal"); // 示例样式
                fontSettingMap.put("isDefault", false); // 应用按钮不设为默认

                // 调用保存方法
                fontSettingClient.addFontSetting(userId, fontName, size, "black",
                                String.valueOf(fontStyle), "normal", false)
                        .thenAccept(result -> {
                            SwingUtilities.invokeLater(() -> {
                                if (result != null) {
                                    System.out.println("字体设置已保存");
                                } else {
                                    JOptionPane.showMessageDialog(
                                            MainFrame.this,
                                            "保存字体设置失败",
                                            "错误",
                                            JOptionPane.ERROR_MESSAGE
                                    );
                                }
                            });
                        });
            } else {
                JOptionPane.showMessageDialog(this, "用户未登录，无法保存字体设置", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        // 保存为默认按钮事件
        saveButton.addActionListener(e -> {
            if (userId == null) {
                JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            // 获取当前选择的字体设置 - 声明为final
            final String fontName = (String) fontCombo.getSelectedItem();
            final int size = (Integer) sizeSpinner.getValue();
            final int styleVal = styleCombo.getSelectedIndex();

            // 转换样式为Java Font常量
            final int fontStyle;
            if (styleVal == 1) fontStyle = Font.BOLD;
            else if (styleVal == 2) fontStyle = Font.ITALIC;
            else if (styleVal == 3) fontStyle = Font.BOLD + Font.ITALIC;
            else fontStyle = Font.PLAIN;

            // 获取字体粗细和样式描述
            final String fontWeight;
            final String fontStyleDesc;
            if (fontStyle == Font.BOLD) {
                fontWeight = "bold";
                fontStyleDesc = "normal";
            } else if (fontStyle == Font.ITALIC) {
                fontWeight = "normal";
                fontStyleDesc = "italic";
            } else if (fontStyle == (Font.BOLD + Font.ITALIC)) {
                fontWeight = "bold";
                fontStyleDesc = "italic";
            } else {
                fontWeight = "normal";
                fontStyleDesc = "normal";
            }

            // 调用服务保存为默认设置
            fontSettingClient.addFontSetting(userId, "黑体", 14, "black",
                            fontWeight, fontStyleDesc, true)
                    .thenAccept(result -> {
                        SwingUtilities.invokeLater(() -> {
                            if (result != null) {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "字体设置已保存为默认",
                                        "成功",
                                        JOptionPane.INFORMATION_MESSAGE
                                );

                                // 更新当前字体 - 使用final变量
                                currentFont = new Font("黑体", fontStyle, 14);
                                messageArea.setFont(currentFont);
                                messageInput.setFont(currentFont);

                                // 更新对话框中的选择项
                                fontCombo.setSelectedItem("黑体");
                                sizeSpinner.setValue(14);
                                styleCombo.setSelectedIndex(styleVal);

                                // 更新预览
                                previewLabel.setFont(currentFont);
                            } else {
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "保存字体设置失败",
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        });
                    })
                    .exceptionally(ex -> {
                        System.err.println("保存默认字体设置失败: " + ex.getMessage());
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    "保存默认字体设置异常: " + ex.getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        });
                        return null;
                    });
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(applyButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel);

        dialog.add(panel);
        dialog.setVisible(true);
    }

    // 新增：显示通知中心对话框
    // 显示通知中心对话框
    private void showNotificationCenterDialog() {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "通知中心", true);
        dialog.setSize(600, 500);
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());

        JTextArea notificationsArea = new JTextArea();
        notificationsArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(notificationsArea);
        panel.add(scrollPane, BorderLayout.CENTER);

        JPanel buttonPanel = new JPanel();
        //JButton markAllAsReadButton = new JButton("标记全部已读");
        JButton refreshButton = new JButton("刷新");

//        markAllAsReadButton.addActionListener(e -> {
//            notificationClient.markAllNotificationsAsRead(userId).thenAccept(response -> {
//                SwingUtilities.invokeLater(() -> {
//                    if (response != null && response.get("status").equals("success")) {
//                        JOptionPane.showMessageDialog(
//                                MainFrame.this,
//                                "所有通知已标记为已读",
//                                "成功",
//                                JOptionPane.INFORMATION_MESSAGE
//                        );
//                        notificationBadge.setText("0");
//                        loadNotifications(notificationsArea);
//                    } else {
//                        JOptionPane.showMessageDialog(
//                                MainFrame.this,
//                                "标记通知失败",
//                                "错误",
//                                JOptionPane.ERROR_MESSAGE
//                        );
//                    }
//                });
//            });
//        });

        refreshButton.addActionListener(e -> loadNotifications(notificationsArea));

        //buttonPanel.add(markAllAsReadButton);
        buttonPanel.add(refreshButton);
        panel.add(buttonPanel, BorderLayout.SOUTH);

        dialog.add(panel);
        dialog.setVisible(true);

        loadNotifications(notificationsArea);
    }
    // 新增：加载通知
    // 加载通知并显示状态
    private void loadNotifications(JTextArea notificationsArea) {
        if (userId == null) return;

        notificationsArea.setText("正在加载通知...");

        notificationClient.getNotifications(userId).thenAccept(notifications -> {
            SwingUtilities.invokeLater(() -> {
                if (notifications != null && !notifications.isEmpty()) {
                    notificationsArea.setText("");
                    for (Notifications notification : notifications) {
                        // 根据status显示不同状态
                        String statusText;
                        switch (notification.getStatus()) {
                            case 1:
                                statusText = "[未读]";
                                break;
                            case 2:
                                statusText = "[已读]";
                                break;
                            case 3:
                                statusText = "[已处理]";
                                break;
                            default:
                                statusText = "[未知状态]";
                        }

                        notificationsArea.append(String.format("%s [%s] %s\n",
                                statusText,
                                notification.getCreateTime(),
                                notification.getContent()));
                    }
                } else {
                    notificationsArea.setText("暂无通知");
                }
            });
        });
    }

    // 新增：检查新通知
    // 检查新通知
    private void checkNewNotifications() {
        if (userId == null) return;

        notificationClient.getUnreadNotifications(userId).thenAccept(notifications -> {
            SwingUtilities.invokeLater(() -> {
                int unreadCount = notifications != null ? notifications.size() : 0;
                notificationBadge.setText(String.valueOf(unreadCount));
            });
        }).exceptionally(ex -> {
            System.err.println("检查新通知失败: " + ex.getMessage());
            return null;
        });
    }

    // 新增：显示编辑资料对话框
    private void showEditProfileDialog() {
        if (userId == null) {
            JOptionPane.showMessageDialog(this, "用户未登录", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        JDialog dialog = new JDialog(this, "编辑资料", true);
        dialog.setSize(400, 550); // 增加了一点高度以容纳所有字段
        dialog.setLocationRelativeTo(this);

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(0, 1, 10, 10));
        panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 用户名
        JTextField usernameField = new JTextField(username, 20);
        panel.add(new JLabel("用户名:"));
        panel.add(usernameField);

        // 签名
        JTextField signatureField = new JTextField(signature, 20);
        panel.add(new JLabel("个性签名:"));
        panel.add(signatureField);

        // 手机号
        JTextField phoneField = new JTextField(phone, 20);
        panel.add(new JLabel("手机号:"));
        panel.add(phoneField);

        // 邮箱
        JTextField emailField = new JTextField(email, 20);
        panel.add(new JLabel("邮箱:"));
        panel.add(emailField);

        // 按钮
        JPanel buttonPanel = new JPanel();
        JButton saveButton = new JButton("保存");
        JButton cancelButton = new JButton("取消");

        saveButton.addActionListener(e -> {
            String newUsername = usernameField.getText().trim();
            String newSignature = signatureField.getText().trim();
            String newPhone = phoneField.getText().trim();
            String newEmail = emailField.getText().trim(); // 获取头像URL

            // 输入验证
            if (newUsername.isEmpty()) {
                JOptionPane.showMessageDialog(
                        MainFrame.this,
                        "用户名不能为空",
                        "输入错误",
                        JOptionPane.WARNING_MESSAGE
                );
                return;
            }

            Users user = new Users();
            user.setUserId(userId);
            user.setUsername(newUsername);
            user.setSignature(newSignature);
            user.setPhone(newPhone);
            user.setEmail(newEmail);

            userClient.updateUserInfo(userId, user)
                    .exceptionally(ex -> {
                        // 处理异步异常
                        SwingUtilities.invokeLater(() -> {
                            JOptionPane.showMessageDialog(
                                    MainFrame.this,
                                    "网络请求失败: " + ex.getMessage(),
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        });
                        return null;
                    })
                    .thenAccept(response -> {
                        SwingUtilities.invokeLater(() -> {
                            try {
                                if (response != null && response.get("code").equals(200)) {
                                    JOptionPane.showMessageDialog(
                                            MainFrame.this,
                                            "资料更新成功",
                                            "成功",
                                            JOptionPane.INFORMATION_MESSAGE
                                    );

                                    // 更新本地显示信息
                                    this.username = newUsername;
                                    this.signature = newSignature;
                                    this.phone = newPhone;
                                    this.email = newEmail;

                                    setTitle("即时通讯软件 - " + this.username);
                                    dialog.dispose();
                                } else {
                                    String errorMsg = response != null ?
                                            response.get("message").toString() : "未知错误";
                                    JOptionPane.showMessageDialog(
                                            MainFrame.this,
                                            "资料更新失败: " + errorMsg,
                                            "错误",
                                            JOptionPane.ERROR_MESSAGE
                                    );
                                }
                            } catch (Exception ex) {
                                // 处理响应解析异常
                                JOptionPane.showMessageDialog(
                                        MainFrame.this,
                                        "处理响应失败: " + ex.getMessage(),
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        });
                    });
        });

        cancelButton.addActionListener(e -> dialog.dispose());

        buttonPanel.add(saveButton);
        buttonPanel.add(cancelButton);
        panel.add(buttonPanel);

        dialog.add(panel);
        dialog.setVisible(true);
    }
}